﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WaterRevenueMS.WebUI.Common;
using System.ComponentModel.Composition;
using WaterRevenueMS.Core.Service.ReadMeterMS;
using WaterRevenueMS.Core.Service.BaseData;
using WaterRevenueMS.WebUI.Extension.Filters;
using WaterRevenueMS.Domain.Common.Models;
using WaterRevenueMS.Componnent.Common;
using System.Linq.Expressions;
using WaterRevenueMS.Componnent.Entities.ReadMeterMS;
using WaterRevenueMS.WebUI.Extension.MvcHelper;
using WaterRevenueMS.Domain.ViewModels.BaseData.Area;
using WaterRevenueMS.Domain.ViewModels.BaseData.MeterBook;
using WaterRevenueMS.Domain.ViewModels.BaseData.MeterReader;
using WaterRevenueMS.Domain.ViewModels.ReadMeterMS.TaskTemplet;
using System.Text;

namespace WaterRevenueMS.WebUI.Controllers
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class TaskTempletController : AdminController
    {
        [Import]
        private ITaskTempletService TaskTempletService { get; set; }
        [Import]
        private IAreaService AreaService { get; set; }
        [Import]
        private IMeterBookService MeterBookService { get; set; }
        [Import]
        private IMeterReaderService MeterReaderService { get; set; }

        [AdminLayout]
        public ActionResult Index()
        {
            var model = new TaskTempletModel();
            return View(model);
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        public ActionResult List(DataTableParameter param)
        {
            int total = TaskTempletService.TaskTemplets.Count(t => t.IsDeleted == false && t.IsTaskTemplet==true);

            var expr = BuildSearchCriteria();

            var filterResult = TaskTempletService.TaskTemplets.Where(expr).Select(t => new TaskTempletModel
            {
                Id = t.Id,
                Ren_WMC=t.Ren_WMC,
                Chao_BND=t.Chao_BND,
                Chao_BYD=t.Chao_BYD,
                AreaName=t.Area.Qu_YMC!=null?t.Area.Qu_YMC:"",
                MeterBookName=t.MeterBook.Biao_CMC!=null?t.MeterBook.Biao_CMC:"",
                MeterReaderName=t.MeterReader.Chao_BYMC!=null?t.MeterReader.Chao_BYMC:""

            }).OrderBy(t => t.Id).Skip(param.iDisplayStart).Take(param.iDisplayLength).ToList();

            int sortId = param.iDisplayStart + 1;

            var result = from c in filterResult
                         select new[]
                        {
                            sortId++.ToString(), 
                            c.Ren_WMC,
                            c.Chao_BND.ToString(),
                            c.Chao_BYD.ToString(),
                            c.AreaName,
                            c.MeterBookName,
                            c.MeterReaderName,
                            c.Id.ToString()
                        };

            return Json(new
            {
                sEcho = param.sEcho,
                iDisplayStart = param.iDisplayStart,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }


        public ActionResult Create()
        {
            var model = new TaskTempletModel();
            InitTaskInfo(model);
            return PartialView(model);
        }

        [HttpPost]
        [AdminOperateLog]
        public ActionResult Create(TaskTempletModel model)
        {
            if (ModelState.IsValid)
            {
                OperationResult result = TaskTempletService.Insert(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    return PartialView(model);
                }
            }
            else
            {
                InitTaskInfo(model);
                return PartialView(model);
            }
        }

        public ActionResult Edit(int Id)
        {
            var model = new TaskTempletModel();
            var entity = TaskTempletService.TaskTemplets.FirstOrDefault(t => t.Id == Id);
            if (null != entity)
            {
                model = new TaskTempletModel
                {
                    Id=entity.Id,
                    Ren_WMC=entity.Ren_WMC,
                    Qu_YSZ_No=entity.Qu_YSZ_No,
                    Biao_CSZ_No=entity.Biao_CSZ_No,
                    Chao_BY_No=entity.Chao_BY_No
                };
                InitTaskInfo(model);
            }
            return PartialView(model);
        }

        [HttpPost]
        public ActionResult Edit(TaskTempletModel model)
        {
            if (ModelState.IsValid)
            {
                OperationResult result = TaskTempletService.Update(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    return PartialView(model);
                }

            }
            else
            {
                return PartialView(model);
            }
        }


        public ActionResult Delete(int Id)
        {
            OperationResult result = TaskTempletService.Delete(Id);
            return Json(result);
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        public string GetAreaJson()
        {
            StringBuilder areaJson = new StringBuilder();
            areaJson.Append("[");
            var areas = AreaService.Areas.Where(t => t.IsDeleted == false);
            int count = AreaService.Areas.Count(t => t.IsDeleted == false);
            int i = 0,j=0;
            foreach (var area in areas)
            {
                areaJson.Append("{\"AreaName\":\"").Append(area.Qu_YMC).Append("\",");
                areaJson.Append("\"AreaID\":\"").Append(area.Id).Append("\",");
                areaJson.Append("\"Bldgs\":[");
                j = 0;
                var meterBooks = MeterBookService.MeterBooks.Where(t => t.Qu_YSZ_No == area.Id);
                int num = MeterBookService.MeterBooks.Count(t => t.Qu_YSZ_No == area.Id);
                if (meterBooks != null)
                {
                    foreach (var meterbook in meterBooks)
                    {

                        areaJson.Append("{\"BldgName\":\"").Append(meterbook.Biao_CMC).Append("\",");
                        areaJson.Append("\"BldgID\":\"").Append(meterbook.Id).Append("\"}");
                        if (j != (num - 1))
                        {
                            areaJson.Append(",");
                        }
                        j++;
                    }
                    
                }
                areaJson.Append("]}");
                if(i!=(count-1))
                    areaJson.Append(",");
                i++;
            }
            areaJson.Append("]");
            return areaJson.ToString();
        }

        private Expression<Func<TaskTemplet, Boolean>> BuildSearchCriteria()
        {
            DynamicLambda<TaskTemplet> bulider = new DynamicLambda<TaskTemplet>();
            Expression<Func<TaskTemplet, Boolean>> expr = null;

            Expression<Func<TaskTemplet, Boolean>> tmpSolid = t => t.IsDeleted == false;
            
            expr = bulider.BuildQueryAnd(expr, tmpSolid);
            Expression<Func<TaskTemplet, Boolean>> tmpTemplet = t => t.IsTaskTemplet == true;
            expr = bulider.BuildQueryAnd(expr, tmpTemplet);
            return expr;
        }

        private void InitTaskInfo(TaskTempletModel model)
        {
            var areas = AreaService.Areas.Where(t => t.IsDeleted == false)
                .Select(t => new AreaModel
                {
                    id=t.Id,
                    Qu_YMC=t.Qu_YMC
                });
            foreach (var item in areas)
            {
                model.Areas.Add(new SelectListItem { Text = item.Qu_YMC, Value = item.id.ToString() });
            }

            var meterBooks = MeterBookService.MeterBooks.Where(t => t.IsDeleted == false)
                .Select(t => new MeterBookModel { 
                    id=t.Id,
                    Biao_CMC=t.Biao_CMC
                });
            foreach (var item in meterBooks)
            {
                model.MeterBooks.Add(new SelectListItem { Text = item.Biao_CMC, Value = item.id.ToString() });
            }
            var meterReaders = MeterReaderService.MeterReaders.Where(t => t.IsDeleted == false)
                .Select(t => new MeterReaderModel { 
                    id=t.Id,
                    Chao_BYMC=t.Chao_BYMC
                });
            foreach (var item in meterReaders)
            {
                model.MeterReaders.Add(new SelectListItem {Text=item.Chao_BYMC,Value=item.id.ToString() });
            }

        }


    }
}
